import { reqLogin, reqGetUserInfo, reqGetAvatar } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken(), // token字符串
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // promise封装登录请求
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      // 请求成功 储存 token
      reqLogin(data).then(res => {
        const newToken = res.data
        commit('setToken', newToken)
        resolve(res)
      }).catch(error => {
        // 请求失败  抛出错误
        reject(error)
      })
    })
  },
  async getUserInfo({ commit }) {
    const { data: res1 } = await reqGetUserInfo()
    const { data: res2 } = await reqGetAvatar(res1.userId)
    const result = {
      ...res1, ...res2
    }
    commit('setUserInfo', result)
    return result
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    resetRouter()
    commit('permission/setRoutes', [], { root: true }) // 全局的
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
